package com.example.wengwyue.patientapplication.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;

import com.example.wengwyue.patientapplication.activity.LoginActivity;
import com.example.wengwyue.patientapplication.network.API;
import com.hospital.common.BaseApplication;
import com.hospital.common.api.CallbackUtils;
import com.hospital.common.util.BaseConfig;
import com.hospital.common.util.LocalBroadcasts;


/**
 * 应用的基类，封装一些应用全局调用的对象及API（to be continued），
 * 
 * 包括提供全局的Handler对象和Application Context，
 * 
 * 也提供了强杀进程等方法。
 * 
 * @author yong01.yin
 *
 */
public class PatientApplication extends BaseApplication {
	
	private static Handler sHandler;

    @Override
    public void onCreate() {
        super.onCreate();


	}

	@Override
	protected void onPostCreate() {
		super.onPostCreate();
		initLocalBroadcast();
		initAppConfig();	// app配置，后续考虑 是否添加判断主进程
	}

	/**
	 * @return 整个APP可以使用的Handler（为主线程）
	 */
	public static Handler getHandler() {
		checkHandler();
		return sHandler;
	}

	private static void checkHandler() {
		if (null == sHandler) {
			sHandler = new Handler(Looper.getMainLooper());
		}
	}

	/**
	 * 强杀本进程
	 */
	public static void killProcess() {
		Process.killProcess(Process.myPid());
	}

	private void initAppConfig() {
		BaseConfig.ServerDomain = API.ServerDomain;
		BaseConfig.BaseUrl = API.BaseUrl;
	}
	private void initLocalBroadcast() {
		LocalBroadcasts.registerLocalReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (CallbackUtils.TOKEN_INVAILD_FAILED.equals(action)) {
					Intent newIntent = new Intent(context, LoginActivity.class);
					newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
					startActivity(newIntent);
				}
			}
		}, CallbackUtils.TOKEN_INVAILD_FAILED);
	}

}
